package com.weme.home.fragment

import android.graphics.Rect
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.Log
import android.view.View
import androidx.fragment.app.activityViewModels
import androidx.media3.common.MediaItem
import androidx.media3.common.Player.*
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.ui.AspectRatioFrameLayout
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.jeremyliao.liveeventbus.LiveEventBus
import com.purepulse.home.R
import com.purepulse.home.databinding.FragmentHomeHotBinding
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.weme.common.arouter.ARouterHelper
import com.weme.common.base.BaseFragment
import com.weme.common.network.OnLineErrorBean
import com.weme.common.util.*
import com.weme.common.view.MyStyledPlayerView
import com.weme.home.adapter.HomeAdapter
import com.weme.home.viewmode.HomeHotViewMode
import com.weme.home.viewmode.HomeViewMode
import dev.kratos.api.user_server.v1.GetOnlineListReply
import dev.kratos.api.user_server.v1.Users
import java.lang.ref.WeakReference
import java.util.*


class HomeHotFragment : BaseFragment<FragmentHomeHotBinding, HomeHotViewMode>() {
    private var pageIndex: Int = 1
    private val mViewModel: HomeViewMode by activityViewModels()

    //  private var requestOptions = RequestOptions()
    private var showActivity = true
    private var oldPosition = 0

    private var visibleCount = 0
    private var usersList = mutableListOf<Users>()
    private var palyVideoVidw: MyStyledPlayerView? = null
    private var player: ExoPlayer? = null
    private var secondHandler: HomeHotHandle? = null
    private val autoVideo = 999

    private var homeAdapter: HomeAdapter? = null
    override fun startOperate() {
        homeAdapter = HomeAdapter {
            viewModel.callsPhone(it)
        }
        initRecyclerView()
        initRefreshLayout()
        LiveEventBus.get<Any>(LiveConfig.NET_WORK_HOME_HOT).observe(this) {
            if (it is GetOnlineListReply) {
                if (pageIndex == 1) {
                    usersList.clear()
                    usersList.addAll(it.usersList)
                    homeAdapter?.submitList(usersList)
                    mBinding.rcvHomeList.scrollToPosition(0)
                    mBinding.inEmpty.root.setVisible(it.usersCount == 0)
                } else {
                    usersList.addAll(it.usersList)
                    homeAdapter?.addAll(it.usersList)
                }


                mBinding.refreshHome.finishRefresh()
                mBinding.refreshHome.finishLoadMore()
            } else if (it is OnLineErrorBean) {
                if (pageIndex == 1) {
                    mBinding.inEmpty.root.visible()
                    usersList.clear()
                    homeAdapter?.notifyDataSetChanged()
                }
                mBinding.refreshHome.finishRefresh()
                mBinding.refreshHome.finishLoadMore()
            }
        }
    }

    private val autoPlayDelay = 500L
    private var isScrolling = false


    class HomeHotHandle(homeHotFragment: HomeHotFragment) : Handler(Looper.getMainLooper()) {

        private val weakReference: WeakReference<HomeHotFragment> = WeakReference(homeHotFragment)

        override fun handleMessage(msg: Message) {
            val host = weakReference.get()
            if (host != null) {
                when (msg.what) {
                    host.autoVideo -> {
                        host.isScrolling = false
                        if (host.showActivity) {
                            host.context?.run {
                                host.watchVideo((msg.obj as MyStyledPlayerView))
                            }
                        }
                    }

                }
            }
        }
    }


    private fun initRecyclerView() {
        secondHandler = HomeHotHandle(this)
        mBinding.rcvHomeList.apply { //            val gridLayoutManager = GridLayoutManager(requireContext(), 2)
            //            gridLayoutManager.recycleChildrenOnDetach = false
            //            layoutManager = gridLayoutManager
            setHasFixedSize(true) //优化布局 固定宽高的作用
            setHasTransientState(true)
            // itemAnimator = null
            setItemViewCacheSize(20) // 设置可回收的 item 视图数量为 20

            adapter = homeAdapter

            mBinding.inEmpty.btRefresh.text =
                getString(com.example.resources.R.string.home_empty_btn)
            // mBinding.inEmpty.btRefresh.setBackgroundResource(com.example.resources.R.mipmap.icon_empty_home_btn)
            mBinding.inEmpty.tvEmpty.text = getString(com.example.resources.R.string.home_empty_msg)
            mBinding.inEmpty.btRefresh.setOnClickListener {
                mBinding.refreshHome.autoRefresh()
            }

            homeAdapter?.submitList(usersList)
            addOnChildAttachStateChangeListener(object :
                RecyclerView.OnChildAttachStateChangeListener {
                override fun onChildViewAttachedToWindow(view: View) { //  Log.e("tag", "rcvHomeList 恢复")
                }

                override fun onChildViewDetachedFromWindow(view: View) { //                    Log.e("tag", "rcvHomeList 回收") //   stopVideo()
                }

            })
            addOnScrollListener(object : RecyclerView.OnScrollListener() {
                override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                    super.onScrollStateChanged(recyclerView, newState)
                    if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                        if (!isScrolling) {
                            isScrolling = true
                            autoPlayVideo(recyclerView)
                        }
                    } else { // 非 SCROLL_STATE_IDLE，重新计时
                        isScrolling = false
                        secondHandler?.removeMessages(autoVideo) //handler.removeCallbacksAndMessages(null)
                        stopVideo()
                    }
                }

                override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                    super.onScrolled(recyclerView, dx, dy)
                    val layoutManager = recyclerView.layoutManager
                    if (layoutManager is LinearLayoutManager) {
                        visibleCount =
                            layoutManager.findLastVisibleItemPosition() - layoutManager.findFirstVisibleItemPosition()
                    }
                }
            })
            homeAdapter?.setOnItemClickListener { _, _, position ->
                ARouterHelper.navigateToUserInfoActivity(
                    requireActivity(),
                    homeAdapter!!.items[position].uid
                )

            }
        }
        mBinding.rcvHomeList.setRecycledViewPool(mViewModel.recycledViewPool)
    }

    private fun initRefreshLayout() {
        mBinding.refreshHome.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                pageIndex = 1
                viewModel.getOnlineList(pageIndex)
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                pageIndex++
                viewModel.getOnlineList(pageIndex)
            }
        })
    }


    override fun onPause() {
        super.onPause()
        showActivity = false
        stopVideo()
    }

    override fun onResume() {
        super.onResume()
        showActivity = true
        pageIndex = 1
        viewModel.getOnlineList(pageIndex)
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        showActivity = !hidden
    }

    private fun autoPlayVideo(recyclerView: RecyclerView) {
        val layoutManager = recyclerView.layoutManager
        for (i in 0 until 2) {

            if ((layoutManager?.getChildAt(i) != null) && (layoutManager.getChildAt(i)!!
                    .findViewById<MyStyledPlayerView>(R.id.myVideoView) != null)
            ) {
                val styleMediaPlayerView =
                    recyclerView.getChildAt(i).findViewById<MyStyledPlayerView>(R.id.myVideoView)
                val rect = Rect()
                styleMediaPlayerView.getLocalVisibleRect(rect)
                val videoHeight = styleMediaPlayerView.height
                Log.e("homevideo", (rect.bottom - rect.top).toString())
                val position = layoutManager.getPosition(layoutManager.getChildAt(i)!!)
                Log.e("homevideo", "layoutManager 在 列表中的位置=$position")
                if (rect.top == 0 && rect.bottom == videoHeight) {
                    val isVideo = homeAdapter!!.getItem(position)!!.mediaList.any { item ->
                        !item.type.isTypeImg()
                    }
                    if (isVideo) {
                        Log.e(
                            "homevideo",
                            "开始播放第" + i + "个item视频" + styleMediaPlayerView.videoUri
                        )
                        val msg = secondHandler?.obtainMessage()
                        msg?.let {
                            msg.what = autoVideo
                            msg.obj = styleMediaPlayerView
                            secondHandler?.sendMessageDelayed(msg, autoPlayDelay)
                        }

                        break
                    }
                }
            }
        }
    }


    private fun watchVideo(itemView: MyStyledPlayerView) {
        if (itemView.videoUri.isEmpty()) {
            Log.e("homevideo", "没找到视频地址")
            return
        }
        if (itemView.isPlay()) {
            Log.e("homevideo", "已经在播放了")
            return
        }
        playVideo(itemView)
    }

    @androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)
    private fun playVideo(itemView: MyStyledPlayerView) {
        stopVideo()
        Log.e("homevideo", "替换view")
        palyVideoVidw = itemView
        palyVideoVidw?.let {

            player = ExoPlayer.Builder(requireContext()).build()
            player?.addListener(object : Listener {
                override fun onPlaybackStateChanged(playbackState: Int) {
                    super.onPlaybackStateChanged(playbackState)
                    Log.e("homevideo", "播放器状态$playbackState")
                    when (playbackState) {
                        STATE_IDLE -> { // 播放器处于空闲状态
                        }

                        STATE_BUFFERING -> { // 播放器正在缓冲
                        }

                        STATE_READY -> { // 播放器已准备好播放
                            palyVideoVidw?.startVideo()
                        }

                        STATE_ENDED -> { // 播放已结束
                        }
                    }
                }

            })
            itemView.videoUri.forEach {
                val mediaItem = MediaItem.fromUri(it)
                player?.addMediaItem(mediaItem)
            }

            itemView.getVideoView().player = player
            itemView.getVideoView().resizeMode = AspectRatioFrameLayout.RESIZE_MODE_ZOOM
            player?.volume = 0f
            player?.repeatMode = REPEAT_MODE_ALL
            player?.prepare()
            player?.playWhenReady = true // player?.play()
            //   it.startVideo()
        } //  palyVideoVidw?.startVideo()

    }


    private fun stopVideo() {
        palyVideoVidw?.apply {
            Log.e("homevideo", "停止播放$oldPosition")
            stopVideo()
            player?.playWhenReady = false
            player?.release()
        }

    }


    override fun clickListener() {

    }

    override fun getViewModel(): Class<HomeHotViewMode> = HomeHotViewMode::class.java
}
